#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os, sys
import jpype
from pytools.hbaseservice import HBaseService

reload(sys)
sys.setdefaultencoding('utf-8')


def dump_result(listscfmap, fd, fields):
    for i in range(listscfmap.size()):
        scfmap = listscfmap.get(i).getScfMap()
        # print scfmap['rowKey']
        fd.write(','.join([scfmap[f] for f in fields]) + '\n')


def get_all_cat_and_local_of_the_day(day, table):
    hbase = HBaseService()

    fielddict = {'DetailLogCount':['cf:time', 'cf:cate', 'cf:area', 'cf:detailPv', 'cf:detailUv', 'cf:vistsCount', 'cf:listToPv', 'cf:souOutPv', 'cf:souToPv'],
            'ListAnalytics':['cf:actionDate', 'cf:actionCate', 'cf:actionArea', 'cf:actionPv', 'cf:actionUv', 'cf:actionVisit', 'cf:actionLand', 'cf:actionToDetailPv', 'cf:actionToDetailUv', 'cf:actionOnePv', 'cf:actionOneToDetailPV', 'cf:actionNoResult', 'cf:actionMoreResult', 'cf:actionVisitResult', 'cf:actionBounce', 'cf:actionExit', 'cf:actionType']}

    if table not in fielddict:
        print 'ERROR: table does not exist !!!'
        sys.exit(1)

    prefix = day + '_'
    # prefix = '20121115_0_1213'
    print '\n\n'
    print prefix
    print table
    print '\n\n'
    fd = open('./data/' + table + '-' + day + '.txt', 'wb')
    rt = hbase.nextPagesByKeyPrefix(table, prefix, dump_result, fd, fielddict[table])
    if rt is False:
        sys.exit(1)


if __name__ == '__main__':
    if len(sys.argv) != 3:
        print 'usage: %s <20120313> <tablename in hbase>' % (sys.argv[0])
        sys.exit(1)

    day = sys.argv[1]
    table = sys.argv[2]
    get_all_cat_and_local_of_the_day(day, table)
